package com.jason.apps.dashboard;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.apps.essentials.ConsumeWebService;
import com.apps.realtyportal.R;
import com.jason.apps.alert.AlertDialogFragment;
import com.jason.apps.alert.EmptyAlert;
import com.jason.apps.notify.GMailSender;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TextView;

@SuppressLint("ParserError")

public class AddProperty extends SherlockFragment implements OnItemSelectedListener {
	
	public static AddOnClickSelectedListener mCallback;
	
	public EditText Pname;
	public EditText price;
	public EditText address;
	public EditText description;
	public EditText ammenitiespath;
	public EditText imagepath;
	public EditText imagepathammenities;
	public EditText imagepathpanorama;
	public EditText ammenities_description;
	public Button browsepicture;
	public Button addproperty;
	public Button browseammenities;
	public Spinner agentspinner;
	public Spinner propertytype;
	public Spinner sellingtype;
	public Spinner status;
	public ImageButton map;
	
	
	public static final String KEY_FIRSTNAME = "firstName";
	public static final String KEY_LASTNAME = "lastName";
	public static final String KEY_ID = "person_id";
	public static final String KEY_EMAILADDRESS = "emailAddress";

	
	final static ArrayList<HashMap<String, String>> Names = new ArrayList<HashMap<String, String>>();
	
	HashMap<String, String> personsName;
	List<String> labels = new ArrayList<String>();
	List<Integer> ids = new ArrayList<Integer>();
	List<String> email = new ArrayList<String>();
	
	String host = "property-portal.uphero.com";
	String ftpuser = "a5596663";
	String ftppass = "ranger123";
	String saveLocation = "/public_html";
	String folderLocation = "/image/";
	static int agentId=0;
	static String agentEmail=null;
	public TextView maploc;
	FTPClient con = null;
	String longitude;
	String latitude;
	
	SherlockFragmentActivity fa;
	ConsumeWebService consume=new ConsumeWebService();
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view=inflater.inflate(R.layout.addproperty, container, false);
		fa = (SherlockFragmentActivity) super.getActivity();
		
		 Pname=(EditText)view.findViewById(R.id.Pname);
		 price=(EditText)view.findViewById(R.id.price);
		 address=(EditText)view.findViewById(R.id.address);
		 description=(EditText)view.findViewById(R.id.description);
		 imagepath=(EditText)view.findViewById(R.id.imagepath);
		 imagepathammenities=(EditText)view.findViewById(R.id.imagepath_ammenities);
		 imagepathpanorama=(EditText)view.findViewById(R.id.imagepath_panorama);
		 ammenities_description=(EditText)view.findViewById(R.id.ammenities_description);
		 browsepicture=(Button)view.findViewById(R.id.browsepicture);
		 addproperty=(Button)view.findViewById(R.id.addproperty);
		 agentspinner=(Spinner)view.findViewById(R.id.agentspinner);
		 propertytype=(Spinner)view.findViewById(R.id.propertytype);
		 sellingtype=(Spinner)view.findViewById(R.id.propertyselling);
		 map=(ImageButton)view.findViewById(R.id.browsemap);
		 maploc = (TextView)view.findViewById(R.id.map);
		 
		 labels.clear();
		 
		 agentspinner.setOnItemSelectedListener(this);
		 new AddProp().execute();

		 setLocation();
		 addproperty.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if((!Pname.getText().toString().trim().equals(""))&&(!price.getText().toString().trim().equals(""))&&(!address.getText().toString().trim().equals(""))&&(agentId!=0)&&(!latitude.equals(""))&&(!longitude.equals(""))){
					new Add().execute();
				}
				else{
					FragmentManager fm = getActivity().getSupportFragmentManager();
				     EmptyAlert alert = new EmptyAlert();
				     alert.show(fm, "Alert_Dialog");
				     
				}
			}
		});
	
		
		return view;
    }
	@Override
	public void onSaveInstanceState(Bundle arg0) {
		super.onSaveInstanceState(arg0);
		arg0.putString("name", Pname.getText().toString());
		arg0.putString("price", price.getText().toString());
		arg0.putString("address", address.getText().toString());
		arg0.putString("image", imagepath.getText().toString());
		
	};
	@Override
	public void onStart() {
		super.onStart();
		//labels.clear();
		//new AddProp().execute();
	};
	
	public void setUrl(String url){
		imagepath.setText(url);
	}
	public void setUrlAmmenities(String url){
		imagepathammenities.setText(url);
	}
	public void setUrlPanorama(String url){
		imagepathpanorama.setText(url);
	}
	public void setLongLat(String lon,String lat){
		
		maploc.setText(lon+"-"+lat);	
		latitude=lat;
		longitude=lon;
		
	}
	public void setLocation(){
		if((ManageProperty.strlat!=null)&&(ManageProperty.strlon!=null)){
			maploc.setText("Location"+ManageProperty.strlat+""+""+ManageProperty.strlon);		
		}
		
	}
	public List<String> getAllLabels(){

	        String data = consume.getAllPerson();
			 
			 try {
				 	labels.add("None");
				 	ids.add(0);
				 	email.add("nothing");
					JSONArray array = new JSONArray(data);
					
					for (int i = 0; i < array.length(); i++) {
						//personsName=new HashMap<String, String>();
						JSONObject e = array.getJSONObject(i);
						labels.add(e.getString(KEY_FIRSTNAME)+" "+e.getString(KEY_LASTNAME));
						ids.add(e.getInt(KEY_ID));
						email.add(e.getString(KEY_EMAILADDRESS));
						//labels.add(personsName);
					}
				} catch (JSONException e) {
					Log.e("log_tag", "Error parsing data " + e.toString()+"diri jud");
				}finally{
					
				}
	        
	        return labels;
	    }

	public void loadSpinner(Spinner agent){

		ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_spinner_item, labels);
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        agent.setAdapter(dataAdapter);
        agent.setOnItemSelectedListener(this);
        
	}
	//Asynctask
	@SuppressLint({ "NewApi", "NewApi" })
	public class Add extends AsyncTask<Void, Void, Void> {

	    ProgressDialog dialog;;
	    boolean results=false;

	    protected void onPreExecute() {
	    	dialog = new ProgressDialog(fa);
	            dialog.setMessage("Loading...");
	            dialog.show();
	    }


	    protected Void doInBackground(final Void... unused) {

	    	String propertyname=Pname.getText().toString();
	    	String Address=address.getText().toString();
	    	String Pprice=price.getText().toString();
	    	String Pdescription=description.getText().toString();
	    	String Pimagepath=imagepath.getText().toString();
	    	String getPType=propertytype.getSelectedItem().toString();
	    	String filenamePicture=new File(Pimagepath).getName();
	    	String selltype=sellingtype.getSelectedItem().toString();
	    	String ammen=imagepathammenities.getText().toString();
	    	String ammenDescription=ammenities_description.getText().toString();
	    	String pano=imagepathpanorama.getText().toString();

	    			
	    	con = new FTPClient();
			try {
				

				if((!Pimagepath.trim().equals(""))){
					
					con.connect(host);
					
					if((agentId!=0)&&(agentEmail!="nothing")){

							con.login(ftpuser, ftppass);
							
							con.enterLocalPassiveMode(); // important!
							con.setFileType(FTP.BINARY_FILE_TYPE);
							//property picture
							BufferedInputStream buffIn = null;
							buffIn = new BufferedInputStream(
							new FileInputStream(new File(Pimagepath)));
							
							boolean result1 = con.storeFile(saveLocation
							+ folderLocation + filenamePicture, buffIn);
					
							buffIn.close();
							
							if (result1){
								
							Log.v("upload result", "succeeded");
							con.logout();
							con.disconnect();
							
							results=consume.AddProperty(propertyname, Address, Pprice, Pdescription, longitude, latitude, agentId, getPType, "Available","http://"+host+folderLocation+filenamePicture,selltype,"http://"+host+folderLocation+ammen,ammenDescription,"http://"+host+folderLocation+pano);
							
							if(results){
								try {   
									GMailSender sender = new GMailSender("jesonenerez@gmail.com", "jesonenerez");
									sender.sendMail("This is Subject",   
											"You are assigned by the St.therese to this property"+Pname.getText().toString(),   
											"jesonenerez@gmail.com",   
											agentEmail);   
									Log.e("Message", "Na sent bai");
								} catch (Exception e) {   
									Log.e("SendMail", e.getMessage(), e);   
								} 

							}
							
						}
							
						
					}
					else{
						results=consume.AddProperty(propertyname, Address, Pprice, Pdescription, longitude, latitude, agentId, getPType, "Available",Pimagepath,selltype,ammen,ammenDescription,pano);
						Log.e("Message", "Na add SA WALAY AGENT");
					}
				}else{
					results=consume.AddProperty(propertyname, Address, Pprice, Pdescription, longitude, latitude, agentId, getPType, "Available",Pimagepath,selltype,ammen,ammenDescription,pano);

					if(results){
						try {   
							GMailSender sender = new GMailSender("jesonenerez@gmail.com", "jesonenerez");
							sender.sendMail("This is Subject",   
									"You are assigned by the St.therese to this property"+Pname.getText().toString(),   
									"jesonenerez@gmail.com",   
									agentEmail);   
							Log.e("Message", "Na sent bai");
						} catch (Exception e) {   
							Log.e("SendMail", e.getMessage(), e);   
						} 

					}
					Log.e("Message", "Na add SA WALAY IMAGE");
				}
		
			} catch (Exception e) {
				Log.e("","wala jud ma add",e);
			}
	   
	        return null; 
	    }
	    protected void onPostExecute(Void result) {
			 
	    	 if(results){
	    		 FragmentManager fm = getActivity().getSupportFragmentManager();
	    		 AlertDialogFragment alert = new AlertDialogFragment();
	    		 alert.show(fm, "Alert_Dialog");
	    		 clearFields();
	    	 }
	    	 else{
	    		 FragmentManager fm = getActivity().getSupportFragmentManager();
	    		 AlertDialogFragment alert = new AlertDialogFragment();
	    		 alert.show(fm, "Alert_Dialog");
	    		 fm.popBackStack();
	    	 }

	    	if (dialog!=null) {
	            dialog.dismiss();
	            }  
	     }
	  }
	public void onItemSelected(AdapterView<?> parent, View view,
			int position, long id) {
		// TODO Auto-generated method stub
		//int posId=parent.getSelectedItemPosition();
	    agentId=ids.get(position);
	    agentEmail=email.get(position);
       
	}
	
    public interface AddOnClickSelectedListener {
        /** Called by HeadlinesFragment when a list item is selected */
        public void AddArticleSelected(View v,int position);
    }
    
	public void onNothingSelected(AdapterView<?> parent) {
		// TODO Auto-generated method stub
		
	}
	
	//Asynctask
		public class AddProp extends AsyncTask<Void, Void, Void> {

		    ProgressDialog dialog;

		    protected void onPreExecute() {
		    	 dialog = new ProgressDialog(fa);
		           dialog.setMessage("Loading...");
		           dialog.show();
		    }


		    protected Void doInBackground(final Void... unused) {
		    	getAllLabels();
		        return null; 
		    }
		    protected void onPostExecute(Void result) {
		    	loadSpinner(agentspinner);
		    	if (dialog!=null) {
		            dialog.dismiss();
		            }  
		     }
		  }
		
		public void clearFields(){
			 Pname.setText("");
			 price.setText("");
			 address.setText("");
			 description.setText("");
			 imagepath.setText("");
			 agentspinner.setSelection(0);
			 propertytype.setSelection(0);
			 
		}

}